package com.bff.gaia.streaming.api.mo.gaia.network.server;

import com.bff.gaia.streaming.api.mo.gaia.network.Hash;

import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Server {

	int serverPort;
	String clsname = "";
	Hash hash = new Hash(this);

	PrintStream log;
	boolean terminated = false;

	public void log(String s) {
		SimpleDateFormat format = new SimpleDateFormat();
		this.log.println(s + format.format(new Date()));
		this.log.flush();
	}

	public PrintStream getLog() {
		return this.log;
	}

	public void setLog(PrintStream log) {
		this.log = log;
	}

	public Server(int serverPort, String clsname) {
		this.log = System.out;
		this.serverPort = serverPort;
		this.clsname=clsname;
	}

	public void set(String key, Double val) {
		this.hash.set(key, val);
	}

	public Double getMax(String key) {
		return this.hash.getMax(key);
	}

	public Double getMin(String key) {
		return this.hash.getMin(key);
	}

	public void run() {
		try {
			this.log("server start ");
			ServerSocket server = this.getServerSocket();
			while(!terminated) {
				Socket client = server.accept();
//				System.out.println("s1  run ");
				Class<?> c = Class.forName(clsname);
//				System.out.println("s2  run "+c.isAssignableFrom(AServerThread.class));
//				System.out.println("s21  run "+AServerThread.class.isAssignableFrom(c));
//				System.out.println("s3  run "+c);
				if(AServerThread.class.isAssignableFrom(c))
				{
					AServerThread d = (AServerThread) c.newInstance();
					d.setServer(this);
					d.setClient(client);
					d.start();
				}
			}
			server.close();
		} catch (Exception var3) {
			var3.printStackTrace();
			System.exit(1);
		}
	}

	private ServerSocket getServerSocket() throws Exception {
		return new ServerSocket(this.serverPort);
	}

	public void stopServer() {
		this.terminated = true;
	}

	public Hash getHash() {
		return hash;
	}
}